package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;
    @RequestMapping("/list")
    @RequiresPermissions(value = {"department:list","部门列表"},logical = Logical.OR)
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo pageInfo = departmentService.query(qo);
        model.addAttribute("result",pageInfo);
        return "/department/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = {"department:delete","部门删除"},logical = Logical.OR)
    public JsonResult delete(Long id){
        try {
            departmentService.delete(id);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult("删除失败",false);
        }
    }

    /*@RequestMapping("/input")
    @GivePermission(name = "部门编辑/增加页面")
    public String input(Long id,Model model){
        if(id != null){
            Department department = departmentService.get(id);
            model.addAttribute("department",department);
        }
        return "/department/input";
    }*/


    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"department:saveOrUpdate","部门新增/编辑"},logical = Logical.OR)
    public JsonResult saveOrUpdate(Department department){
        try {
            if(department.getId() != null){
                departmentService.update(department);
            }else {
                departmentService.save(department);
            }
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult("保存失败",false);
        }
    }
}
